<template>
  <div class="app-container">
    <div class="top-main">
    <el-form class="top-form-fl" :model="param" :inline="true" label-width="auto">
      <el-form-item label="账单号">
        <el-input v-model.trim="param.billNo" placeholder="请输入" clearable> </el-input>
      </el-form-item>
      <el-form-item label="结算流向">
        <el-select v-model="param.invoiceDirection" clearable style="width:100%" placeholder="请选择" >
          <el-option v-for="item in DATA_invoiceDirections" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="结算单位">
        <el-input v-model.trim="param.businessName" clearable placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item label="发票号">
        <el-input v-model.trim="param.invoiceNo" clearable placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item label="发票状态">
        <el-select v-model="param.invoiceStatus" clearable style="width:100%" placeholder="请选择">
          <el-option v-for="item in DATA_invoiceStatuss" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="纳税人识别号">
        <el-input v-model.trim="param.creditCode" clearable placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item label="发票类型">
        <el-select v-model="param.invoiceType" clearable style="width:100%" placeholder="请选择">
          <el-option v-for="item in param.invoiceTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请日期" style="width: 400px;">
        <el-date-picker v-model="param.createDate" clearable type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
    </el-form>
    <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="handleReset">重置</el-button>
      </div>   
    </div>
    <div>
      <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
      <span style="float: right;">
        <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
          <template v-if="isSelectAll">
            <el-button size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
          </template>
          <template v-else>
              <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
          </template>
        </el-tooltip>
        <el-button type="primary" size="small" style="width:80px" :disabled="!selection.length" round @click="" plain>导出</el-button>
      </span>
      <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" @pageChange="onTablePageChange" @redstoneInvoice="redstoneInvoice"
        @showInvoice="showInvoice" @emailInvoice="emailInvoice" @showRedInvoice="showRedInvoice" @applyInvoice="applyInvoice" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
      </Table>
    </div>
    <!-- dialog -->
    <el-dialog width="600" v-model="param.dialogVisible" @close="cancel">
      <div v-if="param.oprType == 'img'" style="text-align: center;">
        <pdfViewer v-for="(item,index) in param.pdfUrl" :key="index" :url="item.url"></pdfViewer>
      </div>
      <div v-if="param.oprType == 'invoice'">
        <div style="margin-bottom: 10px">          
          <span class="_before">开发票</span>
        </div>
        <el-form label-width="200" style="margin: 50px 0 50px 50px;">
          <el-form-item label="企业抬头：">{{ invoice.invoiceTitle || '--'}}</el-form-item>
          <el-form-item label="统一社会信用代码：">{{ invoice.creditCode || '--' }}</el-form-item>
          <el-form-item label="发票：">
            <img-upload ref="invoiceRef" :fileList="fileList" :needOcr="true" :drag="false" @ocrInvoiceNo="ocrInvoiceNo" />
          </el-form-item>
          <el-form-item label="发票号：" style="width: 400px;">
            <el-input v-model.trim="invoice.invoiceNo" placeholder="请输入发票号" />
          </el-form-item>
          <el-form-item label="发票类型：" style="width: 400px;">
            <el-select v-model="invoice.invoiceType" clearable style="width:100%" placeholder="请选择">
              <el-option v-for="item in param.invoiceTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="发票金额：" style="width: 400px;">
            <el-input :formatter="formatterNumberKo" :parser="formatterNumberKo" v-model.trim="invoice.invoiceAmount" placeholder="请输入发票金额" />
          </el-form-item>
        </el-form>
      </div>
      <div v-if="param.oprType == 'redstone'">
        <div style="margin-bottom: 10px">          
          <span class="_before">红冲</span>
        </div>
        <el-form label-width="200" style="margin: 50px 0 50px 50px;">
           <el-form-item label="发票号：" style="width: 400px;">
            <span>{{invoice.invoiceNo || '--'}}</span>
          </el-form-item>
          <el-form-item label="红冲发票：">
            <img-upload ref="invoiceRedRef" :fileList="fileList" :drag="false" />
          </el-form-item>       
        </el-form>
      </div>
       <div v-if="param.oprType == 'email'">
        <div style="margin-bottom: 10px">          
          <span class="_before">发送邮箱</span>
        </div>
        <el-row align="middle">
          <el-col :offset="2" :span="20"><h3>邮箱地址:</h3></el-col>
        </el-row>
          <template v-for="(item,index) in param.emailList" :key="index">
              <el-row align="middle" class="marginTop5">
                <el-col :offset="2" :span="17"> 
                  <el-input v-model="item.email" type="email" clearable placeholder="请输入有效的邮箱地址"  @blur="validateEmail(index)"></el-input>
                </el-col>
                <el-col :offset="1" :span="4">
                  <el-button icon="Delete" type="danger" size="small" circle plain  @click="handleDelete(index)"></el-button>
                  <el-button icon="Plus" type="info" size="small" circle plain @click="handleAdd"></el-button>
                </el-col>
              </el-row>
          </template>
      </div>
      <div style="text-align: center;margin-top: 20px;">
        <div class="dialog-footer">
          <el-button @click="param.dialogVisible = false">关闭</el-button>
          <el-button v-if="param.oprType == 'redstone'" @click="handleSubmit('redstone')" type="primary">确定</el-button>
          <el-button v-if="param.oprType == 'email'" @click="handleSubmit('email')" type="primary">确定</el-button>
          <el-button v-if="param.oprType == 'invoice'" @click="handleSubmit('invoice')" type="primary">提交</el-button>
        </div>
      </div>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import imgUpload from '@/components/upload/index.vue'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import { getInvoicePage, getInvoicesInfo,uploadingInvoice,redReversalInvoice,sendInvoice } from '@/api/invoice/indexNew.ts'
// import pdfViewer from '@/components/pdf/viewer'
import pdfViewer from '@/components/pdf'
import { numMulti, numAdd } from '@/utils/compute'
import { computed, getCurrentInstance, onActivated, onMounted, reactive, ref } from 'vue';
import { View, List, FolderChecked, Ticket } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {DATA_directionFilter,DATA_invoiceDirections,DATA_invoiceStatuss,DATA_invoiceStatusFilter,DATA_stateColor} from '@/data/invoice.js'
import { formatDate,warTime,formatterNumberKo ,inputText,formatterNumber} from '@/utils'
const param = reactive({
  invoiceTypes: [  //5-增值税普通发票  10-增值税专用发票
    { value: 5, label: '增值税普通发票', },
    { value: 10, label: '增值税专用发票', },
  ],
  oprType:'',
  pdfUrl:[],
  loading: false,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  invoiceTypeFilter: { '5': '增值税普通发票', '10': '增值税专用发票' }, //5-增值税普通发票  10-增值税专用发票
  directionFilter: { '-1': '支出', '1': '收入' },
  emailList:[ { "email": "" }],
  typeList: [],
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    // { key: 'releaseRentId', colWidth: '220', title: 'releaseRentId', type: 'text', isCheck: true },   { value: 1, label: '收入', },
    { value: -1, label: '支出', },
    // { key: 'id', colWidth: '220', title: 'ID', type: 'text', isCheck: true },
    { key: 'invoiceNos', colWidth: '220', title: '发票号', type: 'text', isCheck: true },
    { key: 'invoiceOrder', key2: 'billNo', colWidth: '220', title: '账单号', type: '/', isCheck: true },
    { key: 'invoiceDirection', colWidth: '120', title: '结算流向', type: 'filter', filter: param.directionFilter, isCheck: true },
    { key: 'invoiceTitle', colWidth: '100', title: '结算单位', type: 'text', isCheck: true },
    { key: 'creditCode', colWidth: '200', title: '纳税人识别号', type: 'text', isCheck: true },
    { key: 'invoiceType', colWidth: '200', title: '发票类型', type: 'filter', filter: param.invoiceTypeFilter, isCheck: true },
    { key: 'invoiceAmount', colWidth: '200', title: '开票金额', type: 'add', currency: 'currency', isCheck: true },
    // { key: 'operate', colWidth: '100', title: '款项明细', type: 'operate', isCheck: true, buttons: [{ icon: 'List', command: 'activInfo', }] },
    { key: 'invoiceStatus', colWidth: '120', title: '发票状态', type: 'filter', filter: DATA_invoiceStatusFilter, cFilter: DATA_stateColor, isCheck: true },
    { key: 'createTime', colWidth: '200', title: '申请日期', type: 'date', isCheck: true },
    // { key: 'closeStatus', colWidth: '120', title: '结算状态', type: 'filter2', key2:"invoiceSource",roleType:'xd', isCheck: true },
    // { key: 'closeStatus', colWidth: '120', title: '结算状态', type: 'filter2', key2:"invoiceDirection", isCheck: true },
    {
      key: 'operate',
      colWidth: '200',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          name: "查看发票",
          command: 'showInvoice',
          isShow: (row: any) => {
            return row.invoiceStatus >= '15';
          },
        },
        {
          name: "查看红冲发票",
          command: 'showRedInvoice',
          isShow: (row: any) => {
            return row.invoiceStatus == '25';
          },
        },
        {
          name: "开发票",
          command: 'applyInvoice',
          isShow: (row: any) => {
            return row.invoiceStatus < 15;

          },
        },
          {
          name: "红冲",
          command: 'redstoneInvoice',
          isShow: (row: any) => {
            return row.invoiceStatus == '15';

          },
        },
          {
          name: "发送邮箱",
          command: 'emailInvoice',
          isShow: (row: any) => {
            return row.invoiceStatus == '15';

          },
        },
      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}

//初始化
function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    invoiceDirection: param.invoiceDirection,
    billNo: param.billNo?.trim(),
    businessName: param.businessName?.trim(),
    invoiceNo: param.invoiceNo?.trim(),
    invoiceStatus: param.invoiceStatus,
    invoiceType: param.invoiceType,
    creditCode: param.creditCode?.trim(),
  };
  if (param.createDate) {
    data.beginCreateDate = param.createDate[0]
    data.endCreateDate = param.createDate[1]
  }
  table.config.loading = true;
  // 获取列表数据
  getInvoicePage(data).then((res: any) => {
    table.data = JSON.parse(JSON.stringify(res.data.list));
    table.data.map((item: any) => {
      item.invoiceNos = item.invoiceNo
    });
    table.config.total = res.data.total;
  });
  table.config.loading = false;
}

function handleReset() {
  param.invoiceStatus = null
  param.invoiceDirection = null
  param.billNo = null
  param.businessName = null
  param.invoiceNo = null
  param.invoiceStatus = null
  param.invoiceType = null
  param.creditCode = null
  param.createDate = null
  getTableData()
}

// 发票识别
const ocrInvoiceNo = (val: any) => {
  invoice.value.invoiceNo = val.data.invoiceNo
}

//上架/下架  
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  return tableRef.value.multipleSelection.map((item: any) => item.id)
})


// 查看发票
const showInvoice = (row: any) => {
  if (!row.invoiceUrl) return ElMessage.error('未发现发票url')
  param.pdfUrl = JSON.parse(row.invoiceUrl) || []
  param.oprType = 'img'
  param.dialogVisible = true
}
// 查看发票
const showRedInvoice = (row: any) => {
  if (!row.redInvoiceUrl) return ElMessage.error('未发现红冲发票url')
  param.pdfUrl = JSON.parse(row.redInvoiceUrl) || []
  param.oprType = 'img'
  param.dialogVisible = true
}
const invoice = ref({ invoiceType: '5',invoiceAmount:'', })

//开发票
const applyInvoice = (row: any) => {
  param.oprType = 'invoice'
  param.dialogVisible = true
  getDetailAndTotal(row)
}
//红冲
const redstoneInvoice = (row: any) => {
  param.oprType = 'redstone'
  param.dialogVisible = true
  getDetailAndTotal(row)
}
  // 验证邮箱格式
const validateEmail = (index: number) => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(param.emailList[index].email)) {
    param.emailList[index].email = ''; // 清空输入框
    ElMessage.warning('请输入有效的邮箱地址'); // 提示用户
  }
};
//发送邮箱
const emailInvoice = (row: any) => {
  param.oprType = 'email'
  param.dialogVisible = true
  getDetailAndTotal(row)
}
// 添加邮箱输入项目
const handleAdd = () => {
  const data = param.emailList[param.emailList.length - 1] //新增 默认copy最后一行的数据
  const emailItem = JSON.parse(JSON.stringify(data))
  param.emailList.push(emailItem)
}

// 删除邮箱输入项目
const handleDelete = (index: any) => {
  if(param.emailList.length > 1){
    param.emailList.splice(index, 1)
  }else{
    ElMessage.warning("至少要保留一个邮箱")
  }
  
}
// 提交/确定
const invoiceRef = ref({resultList:[]})
const invoiceRedRef=ref({resultList:[]})
const fileList=ref([])
const payRef = ref()
const { proxy } = getCurrentInstance();
const handleSubmit = (oprType: string) => {
  if (oprType == 'invoice') { // 开发票 
    let resultList = invoiceRef.value.resultList || []
    if (resultList.length == 0) {
      return ElMessage({ message: '请上传发票', type: 'warning' })
    }
    if (!invoice.value.invoiceNo) {
      return ElMessage({ message: '请输入发票号', type: 'warning' })
    }
     if (invoice.value.invoiceAmount =='' || invoice.value.invoiceAmount <= 0) {
      return ElMessage({ message: '发票金额不能为空并且大于0', type: 'warning' })
    }
    const data = {
      id: invoice.value.id,
      invoiceNo: invoice.value.invoiceNo,
      invoiceUrl: JSON.stringify(resultList),
      invoiceAmount:invoice.value.invoiceAmount,
      invoiceType:invoice.value.invoiceType,
    }
    uploadingInvoice(data).then((res: any) => {
     ElMessage.success('开发票成功');
      getTableData()
       cancel()
    })
  }
   if (oprType == 'redstone') { // 红冲
    let resultList = invoiceRedRef.value.resultList || []
    if (resultList.length == 0) {
      return ElMessage({ message: '请上传发票', type: 'warning' })
    }
    const data = {
      id: invoice.value.id,
      invoiceNo: invoice.value.invoiceNo,
      redInvoiceUrl: JSON.stringify(resultList),
    }
    redReversalInvoice(data).then((res: any) => {
     ElMessage.success('红冲成功');
      getTableData()
       cancel()
    })
  }
    if (oprType == 'email') { // 发送邮箱
     let emailObj = []
      param.emailList.forEach(item => {
        if(item.email) {
          emailObj.push(item.email)
        }
      })
      const data = {
        id: invoice.value.id,
        email:emailObj
      }
    sendInvoice(data).then((res: any) => {
     ElMessage.success('邮件发送成功');
      getTableData()
      cancel()
    })
  }
}
const cancel=()=>{
  param.dialogVisible = false
  fileList.value=[]
  if(invoiceRedRef.value){
    invoiceRedRef.value.resultList = []
  }
  param.emailList=[ { "email": "" }]
  if(invoiceRef.value){
    invoiceRef.value.resultList = []
  }
  invoice.value.invoiceType='5'
  invoice.value.invoiceAmount=''
  // invoice.value.invoiceNo=''
}
//详情
function getDetailAndTotal(val: any) {
  getInvoicesInfo(val.id).then((res: any) => {
    invoice.value = res.data
  })
}

//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

onActivated(() => {
  getTableData()
})


const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）
const slectAll = async(val:any) =>{
    checkAll.value = []
    await getInvoicePage({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list  && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
}

</script>

<style lang="scss" scoped></style>